/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snake.core.gameinterface;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.Timer;

import snake.core.PositionToComponentNoConverter;
import snake.core.listeners.SnakeActionListener;
import snake.core.listeners.SnakeKeyListener;
import snake.gameplay.Position;
import snake.gameplay.Snake;

/**
 *
 * @author otatarik
 */
public class MainWindow extends JFrame {

    private final int windowSizeX;
    private final int windowSizeY;
    private static final int WINDOW_INIT_COORD_X = 400;
    private static final int WINDOW_INIT_COORD_Y = 400;
    private static final int WINDOW_INIT_WIDTH_Y = 400;
    private static final int WINDOW_INIT_HEIGTH_Y = 400;
    public static final Color FIELD_COLOR = Color.LIGHT_GRAY;
    public static final Color FOOD_COLOR = Color.RED;
    public static final Color SNAKE_COLOR = Color.BLUE;
    private Snake snake;

    public MainWindow(int windowSizeX, int windowSizeY) {
        this.windowSizeX = windowSizeX;
        this.windowSizeY = windowSizeY;
        GridLayout mainGrid = new GridLayout(windowSizeY, windowSizeY, 0, 0);
        getContentPane().setLayout(mainGrid);
        getContentPane().setFocusable(true);

        for (int i = 0; i < windowSizeX * windowSizeY; i++) {
            JPanel panel = new JPanel();
            panel.setBackground(FIELD_COLOR);
            panel.setBorder(BorderFactory.createEmptyBorder());
            getContentPane().add(panel);
        }
        setBounds(WINDOW_INIT_COORD_X, WINDOW_INIT_COORD_Y, WINDOW_INIT_WIDTH_Y, WINDOW_INIT_HEIGTH_Y);
    }

    public void initSnake(Snake snake) {
        this.snake = snake;
        printSnake(snake.getTailPositions());

        Timer timer = new Timer(500, new SnakeActionListener(snake, getContentPane()));
        getContentPane().addKeyListener(new SnakeKeyListener());
        timer.start();
    }

    public void printSnake(List<Position> positionsPrint) {
        for (int i = 0; i < positionsPrint.size(); i++) {
            getContentPane().getComponent(PositionToComponentNoConverter.convert(positionsPrint.get(i))).setBackground(SNAKE_COLOR);
        }
    }
}